define(function (require, exports, module) {
    require("apps/ebom/page.css");
    require("apps/pbom/page.css");
    require("apps/grid");
    require("apps/file");

    exports.init = function (ctx, uuid) {
        var pageListComponent = new $.PageTreeListComponent(uuid, {
            view: {
                grid: "grid",
                myToolbar: "news_tb",
                colbar: "user_list_btn"
            },
            configs: {
                gridUrl: ctx + "/app/api/ebom/list?root=true",
                idField: "id",
                treeField: "eName",
                gridColumns: [
                    {
                        field: 'id',
                        checkbox: true
                    },
                    {
                        field: 'temp1',
                        hidden: true
                    },
                    {
                        field: 'eName',
                        title: '名称',
                        width: 100,
                        align: 'left',
                        formatter: function (value, row, index) {
                            return value + (row.status == 'RECYCLE' ? "（已回收）" : "");
                        }
                    },
                    {
                        field: 'code',
                        title: '编码',
                        width: 100,
                        align: 'left'
                    },
                    {
                        field: 'pBomDes',
                        title: '设计结构',
                        width: 100,
                        align: 'left'
                    },
                    {
                        field: "cover",
                        title: "图片",
                        hidden: true,
                        formatter: function (value, row, index) {
                            return "<img src=\"" + ctx + "/print/" + value + "\" style=\"width:48px;height:32px;\"/>"
                        }
                    },
                    {
                        field: 'bomType',
                        title: '是否装配',
                        width: 100,
                        align: 'left',
                        formatter: function (value, row, index) {
                            if (value == "E_BOM_TYPE_BUILD") {
                                return "已装配";
                            } else {
                                return "未装配";
                            }
                        }
                    },
                    {
                        field: 'remark',
                        title: '备注',
                        hidden: true,
                        width: 50,
                        align: 'left'
                    },
                    {
                        field: 'description',
                        title: '功能',
                        width: 50,
                        align: 'left',
                        hidden: true
                    },
                    {
                        field: 'createTime',
                        title: '创建时间',
                        width: 100,
                        align: 'left'
                    }
                ],
                onExpand: function (row) {
                    if (row.children == undefined) {
                        pageListComponent.grid.treegrid("loadChildren", {
                            url: ctx + "/app/api/ebom/children",
                            row: row
                        });
                    }
                }
            },
            events: {
                renderColBarBefore: function (key, row) {
                    if (key == "work") {
                        return !row.bomGroup;
                    } else if (key == "recycle") {
                        return !row.bomGroup && row.bomType == 'E_BOM_TYPE_BUILD'
                    }else if (key == 'export') {
                        return !row.bomGroup && row.state.length > 0;
                    }else if (key == 'exportAll') {
                        return !row.bomGroup && row.state.length > 0;
                    } else if (key == 'history') {
                        return !row.bomGroup && row.doProcess;
                    }
                    return true;
                },
                onClickColBtn: function (context, btn, row) {
                    switch (btn.key) {
                        case "view":
                            whenView(context, row);
                            break;
                        case "recycle":
                            whenRecycle(context, btn.href, row);
                            break;
                        case "export":
                            whenExport(context, row);
                            break;
                        case "exportAll":
                            whenExportAll(context, row);
                            break;
                        default :
                            break;
                    }
                },
                onClickToolbarBtn: function (context, btn) {
                    switch (btn.key) {
                        case "search_all":
                            context.searchAll();
                            break;
                        case "add":
                            whenAdd(context, btn.href);
                            break;
                        case "search":
                            context.search(btn.href, "装配结构搜索", "ebom_search");
                            break;
                        default :
                            break;
                    }
                }
            }
        });

        var globalWindow = new $.PageWindow();

        function whenAdd(context, href) {
            globalWindow.create({
                href: href,
                title: "结构装配",
                width:1000,
                onClose:function(){
                    context.grid.treegrid("reload")
                }
            });
            globalWindow.open();
        }

        function whenViewDetail(context, row) {
            //获取组成连接
            var pa = context.grid.treegrid("getParent", row.id);
            var parentId = pa.refId ? pa.refId : pa.id,
                curId = row.refId ? row.refId : row.id;
            globalWindow.create({
                width: 700,
                href: ctx + "/app/api/ebom/pBomDetailList?parentId=" + parentId + "&curId=" + curId,
                title: pa.eName + "(" + pa.code + ")" + "的组成结构"
            });
            globalWindow.open();
        }

        function whenView(context, row) {
            if (!row.bomGroup) {
                context.detail("工艺装配结构详情查看", row);
            } else {
                whenViewDetail(context, row);
            }
        }
        function whenExport(context, row) {
            var fileComp = require("apps/file");
            fileComp.download(WE.contextPath + "/app/api/ebom/export?id=" + row.id);
        }

        function whenExportAll(context, row) {
            var fileComp = require("apps/file");
            fileComp.download(WE.contextPath + "/app/api/ebom/packageEBOM?id=" + row.id);
        }

        function whenRecycle(context, href, row) {
            $.messager.confirm("信息", "是否确定要回收该工件，回收后工件可以被用于其他工件的组装？", function (arg) {
                if (arg) {
                    $("body").wait("start", "保存中,请稍候.");
                    $.post(href, {id: row.id}, function (data) {
                        $("body").wait("end");
                        if ($.isPlainObject(data) && data.error) {
                            $.messager.alert('信息',
                                data.msg, 'error');
                        } else {
                            $.messager.alert('信息',
                                "工件回收成功", 'info');
                            context.grid.treegrid("reload");
                        }
                    }, "JSON")
                }
            })
        }
    };
    exports.search = function(ctx, uuid){
        require("apps/lab-search");
        var page = new $.PageDomFactory(uuid, true);
        page.getJqDom("tabPanel").tabs();
        page.getJqDom("beginQuery").datetimebox({
            editable: false
        });
        page.getJqDom("endQuery").datetimebox({
            editable: false
        });
        page.getJqDom("addCondition").labSearch();

        window.ebom_search = function(win) {
            win.wait("start", "搜索中,请稍候.");
            var form = page.getJqDom("form-search-info");
            var data = form.serializeJson();
            var conditions = page.getJqDom("addCondition").labSearch("getData");
            data.conditions = conditions;
            win.callback($.utils.buildJson(data));
            win.wait("end");
            win.close();
        }
    };
    exports.add = function(ctx, uuid){
        function setInfo(pbom, id, children) {
            if (pbom.id == id) {
                pbom.children = children;
                return true;
            } else {
                if (pbom.children && pbom.children.length) {
                    var ex = false;
                    for (var i = 0, l = pbom.children.length; i < l; i++) {
                        ex = setInfo(pbom.children[i], id, children);
                        if (ex) {
                            return ex;
                        }
                    }
                }
                return false;
            }
        }

        var pageListComponent = new $.PageTreeListComponent(uuid, {
            view: {
                grid: "grid",
                myToolbar: "news_tb",
                colbar: "user_list_btn"
            },
            configs: {
                gridTitle: "工艺设计结构列表",
                gridUrl: ctx + "/app/api/pbom/list?root=true&publish=1",
                idField: "id",
                treeField: "pName",
                gridColumns: [
                    {
                        field: 'id',
                        checkbox: true
                    },
                    {
                        field: 'temp1',
                        hidden: true
                    },
                    {
                        field: 'pName',
                        title: '名称',
                        width: 100,
                        align: 'left'
                    },
                    {
                        field: 'code',
                        title: '编码',
                        width: 100,
                        align: 'left'
                    },
                    {
                        field: 'number',
                        title: '数量（件）',
                        width: 50,
                        align: 'left'
                    },
                    {
                        field: 'bomType',
                        title: '制造分类',
                        width: 100,
                        hidden: true,
                        align: 'left'
                    },
                    {
                        field: '_queryNumber',
                        title: '匹配的工件',
                        width: 100,
                        align: 'left',
                        formatter: function (value, row, index) {
                            return "总数：" + row.suitAll + "，未装配：" + row.nonBuild;
                        }
                    },
                    {
                        field: 'status',
                        title: '状态',
                        width: 50,
                        align: 'left',
                        formatter: function (value, row, index) {
                            if (value == "PUBLISH") {
                                return "已发布";
                            } else if (value == "UN_PUBLISH") {
                                return "未发布";
                            } else {
                                return "已废弃";
                            }
                        }
                    },
                    {
                        field: 'remark',
                        title: '备注',
                        hidden: true,
                        width: 50,
                        align: 'left'
                    }
                ],
                onExpand: function (row) {
                    if (row.children == undefined) {
                        pageListComponent.grid.treegrid("loadChildren", {
                            url: ctx + "/app/api/pbom/children",
                            row: row
                        });
                    }
                }
            },
            events: {
                renderColBarBefore: function (key, row) {
                    if (key == "build") {
                        return row.canBuild;
                    } else if (key == 'pBomDetail') {
                        return row.status == "PUBLISH" && row.suitAll > 0;
                    }
                    return true;
                },
                onClickColBtn: function (context, btn, row) {
                    switch (btn.key) {
                        case "view":
                            whenView(context, row);
                            break;
                        case "build":
                            whenBuild(context, row);
                            break;
                        case "pBomDetail":
                            whenViewDetail(context, btn.href, row);
                            break;
                        default :
                            break;
                    }
                },
                onClickToolbarBtn: function (context, btn) {
                    switch (btn.key) {
                        case "search_all":
                            context.searchAll();
                            break;
                        case "search":
                            context.search(btn.href, "设计结构搜索", "pbom_search");
                            break;
                        default :
                            break;
                    }
                }
            }
        });
        var globalWindow = new $.PageWindow();

        function whenBuild(context, row) {
            var id = row.refId ? row.refId : row.id;
            globalWindow.create({
                width: 800,
                href: ctx + "/app/api/ebom/build?id=" + id,
                method: "add_ebom",
                title: "新增结构",
                callback: function (status, postData) {
                    if (status) {
                        //重新请求当前节点和上级节点的数据
                        //获取当前节点的id和父级的id
                        var ids = [postData.pbomId];
                        var parent = context.grid.treegrid("getParent", postData.pbomId);
                        if (parent) {
                            ids.unshift(parent.id);
                        }
                        var children = context.grid.treegrid("getChildren", postData.pbomId);
                        if(children){
                            for(var i = 0, l = children.length; i < l; i++){
                                ids.push(children[i].id);
                            }
                        }
                        $.getJSON(ctx + "/app/api/pbom/list", $.utils.buildJson({ids: ids}), function (data) {
                            var content = data.content;
                            for(var j = 0; j < ids.length; j++){
                                for (var i = 0, l = content.length; i < l; i++) {
                                    if(ids[j] == content[i].id){
                                        var row = context.grid.treegrid("find", content[i].id);
                                        context.grid.treegrid("update", {id: content[i].id, row: $.extend(row, content[i])});
                                        break;
                                    }
                                }
                            }
                        });
                    }
                }
            });
            globalWindow.open();
        }

        function whenViewDetail(context, href, row) {
            var id = row.refId ? row.refId : row.id;
            globalWindow.create({
                width: 700,
                href: href + "?id=" + id,
                title: "匹配的装配结构"
            });
            globalWindow.open();
        }

        function whenView(context, row) {
            context.detail("工艺设计结构详情查看", row);
        }
    };
    exports.build = function (ctx, uuid, config) {
        var page = new $.PageDomFactory(uuid);
        page.getJqDom('uploadCover').baseImageUpload({
            'uploader': ctx + '/app/api/file/uploadTempFile'
        });
        page.getJqDom("number").numberbox();
        rebuildNum();
        var globalWindow = new $.PageWindow();

        function whenShowEBoms(id) {
            globalWindow.create({
                href: ctx + "/app/api/ebom/toSuit?id=" + id,
                title: "查看匹配的装配结构"
            });
            globalWindow.open();
        }

        page.getJqDom("buildNum").numberbox({
            onChange:function(){
                rebuildNum();
            }
        });
        page.getJqDom("view").linkbutton({
            onClick: function () {
                var ul = $(this).closest("ul.build-item");
                whenShowEBoms(ul.attr("data-item"));
            }
        });
        page.getJqDom("choose-radio").on("click", function () {
            var v = $(this).val();
            var ul = $(this).closest("ul.build-item");
            var closeable = ul.find("[data-id=" + v + "]");
            if (closeable.is(":visible")) {
                return;
            }
            ul.find(".choose-one").hide();
            closeable.show();
            renderRange(closeable, ul.attr("data-item"));
            rebuildNum();
        });
        var template = '{{#.}}<div data-id="ebom-item" class="ebom-item" data-item="{{id}}">' +
            '<div class="float-right">' +
            '<a href="javascript:void(0)" iconCls="fa fa-trash fa-lg" plain="true"></a>' +
            '</div>' +
            '<span>名称/编码：</span>{{eName}}{{code}}</div>{{/.}}';

        function renderRange(closeable, id) {
            if (closeable.attr("data-id") != "choose") {
                return;
            }
            if(closeable.attr("data-ref") == "rendered"){
                return;
            }
            closeable.attr("data-ref", "rendered");
            require("apps/easyui");
            closeable.find("[data-id=addTool]").linkbutton({
                onClick:function(){
                    $(this).addClass("clicked");
                    globalWindow.create({
                        href: ctx + "/app/api/ebom/choose?selected=1&bomType=E_BOM_TYPE_UN_BUILD&tPBom.id=" + id,
                        method: "choose_ebom_child",
                        title: "选择已发布的结构",
                        width: 820,
                        callback: function (status, json) {
                            if (status) {
                                var dom = page.getJqDom("addTool").filter(".clicked");
                                var postData = json.postData;
                                if(postData.length){
                                    //检查是否已经包含该结构
                                    var results = [], items = [];
                                    var box =  dom.next();
                                    box.find(".ebom-item").each(function () {
                                        results.push($(this).attr("data-item"));
                                    });
                                    for (var i = 0, l = postData.length; i < l; i++) {
                                        if (!results.contains(postData[i].id)) {
                                            items.push(postData[i]);
                                        }
                                    }
                                    $(Mustache.render(template, items)).prependTo(box.children()).each(function () {
                                        $(this).find("a").linkbutton({
                                            onClick: function () {
                                                $(this).closest(".ebom-item").fadeOut(function () {
                                                    $(this).remove();
                                                    rebuildNum();
                                                });
                                            }
                                        });
                                    });
                                }
                                rebuildNum();
                                page.getJqDom("addTool").removeClass("clicked");
                            }
                        }
                    });
                    globalWindow.open();
                }
            });
        }
        function rendAndGetRandomValue(box, number) {
            var b = box.find("[data-id=buildNum]");
            var suit = b.val();
            suit = parseInt(suit);
            return suit / number;
        }

        function rendAndGetChooseValue(box, number) {
            var selected = box.find(".ebom-item");
            return selected.length / number;
        }

        function rebuildNum() {
            var results = [];
            $(".build-item").each(function () {
                var number = $(this).attr("data-need");
                var box = $(this).find(".choose-one:visible");
                var key = box.attr("data-id");
                number = parseInt(number);
                if (key == "random") {
                    results.push(rendAndGetRandomValue(box, number));
                } else {
                    results.push(rendAndGetChooseValue(box, number));
                }
            });
            var index = -1;
            for (var i = 0; i < results.length; i++) {
                if (index == -1 || results[i] < index) {
                    index = results[i];
                }
            }
            index = index == -1 ? 1 : index;
            page.getJqDom("num").html(index);
            page.getJqDom("number").numberbox("setValue", index);
        }

        window.add_ebom = function(win) {
            var baseForm = page.getJqDom('baseForm');
            if (!baseForm.form('validate')) {
                return false;
            }
            var postData = baseForm.serializeJson();
            if (!postData.number) {
                $.messager.alert('信息',
                    '至少需要装配一个工件', 'error');
                return;
            }
            if (postData.number > 500) {
                $.messager.alert('信息',
                    '系统支持最多一次添加500个工件，如果数量过多请分多次添加', 'error');
                return;
            }
            var itemForms = page.getJqDom('itemForm');
            itemForms.each(function(){
                if(!postData.eBomMakes){
                    postData.eBomMakes = [];
                }
                var eData = $(this).serializeJson();
                var eBomMake = {
                    tpBom:{
                        id:eData.id
                    }
                };
                var key = eData["type_" + eBomMake.tpBom.id];
                if (key == "choose") {
                    var ids = [];
                    $(this).find("[data-id=tool-box]").children().each(function(){
                        ids.push($(this).attr("data-item"));
                    });
                    eBomMake.searchEBomCondition = {
                        ids: ids
                    };
                }
                postData.eBomMakes.push(eBomMake);
            });
            win.wait("start", "保存中,请稍候.");
            $.post(ctx + "/app/api/ebom/add?random=" + Math.random(), $.utils.buildJson(postData),
                function (data) {
                    win.wait("end");
                    if ($.isPlainObject(data) && data.error) {
                        $.messager.alert('信息',
                            data.msg, 'error');
                    } else {
                        var codeDes = data.length > 0 ? (data[0].code + "到" + data[data.length-1].code) : data[0].code
                        $.messager.alert('信息',
                                '装配工件成功，系统为工件分配的编码为' + codeDes, 'info');
                        win.callback(true, {
                            pbomId:config.pBomId
                        });
                        win.close();
                    }
                }, "JSON");
        }
    };
});